﻿
using System.Collections.Generic;
using MossDAL.DotNet;
using System.Xml.Linq;
using MossDAL.Silverlight.ListsService;
using System;
using System.Linq;
using System.Text;
using System.Xml;
using MossDAL.DotNet.ServiceHelpers;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Reflection;
using System.Collections.ObjectModel;

namespace MossDAL.Silverlight.ServiceHelpers
{
    public class SilverlightServiceHelper<T> : BaseServiceHelper<T> where T : SharepointListItem, new()
    {
        private ObservableCollection<T> items = new ObservableCollection<T>();
        public event EventHandler FetchListItemsCompleted;

        protected virtual void OnFetchListItemsCompleted()
        {
            if (FetchListItemsCompleted != null)
            {
                FetchListItemsCompleted(this, EventArgs.Empty);
            }
        }

        public void FetchListItemsAsync(string query)
        {
            if (String.IsNullOrEmpty(SharepointListName))
            {
                MemberInfo info = typeof(T);

                object[] atts = info.GetCustomAttributes(typeof(SharepointListNameAttribute), true);
                if (atts.Count() > 0)
                {
                    SharepointListNameAttribute att = (SharepointListNameAttribute)atts[0];
                    SharepointListName = att.ListName;
                }
            }

            XElement doc = XElement.Parse("<q>" + query + "</q>");
            XElement q = doc.Element("Query");
            XElement viewfields = doc.Element("ViewFields");
            XElement options = doc.Element("QueryOptions");
            Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            ListsSoapClient lc = new ListsSoapClient(binding, new EndpointAddress(ServiceEndpointAddress));
            
            lc.GetListItemsCompleted += new System.EventHandler<GetListItemsCompletedEventArgs>(lc_GetListItemsCompleted);
            lc.GetListItemsAsync(SharepointListName, null, q, viewfields, PageSize.ToString(), options, null);
        }

        public ObservableCollection<T> FetchListItems()
        {
            return items;
        }

        private void lc_GetListItemsCompleted(object sender, GetListItemsCompletedEventArgs e)
        {
            XElement elm = e.Result;
            
            foreach (XElement element in elm.Elements().ToList()[0].Elements())
            {
                T item = new T();
                item.Load(element);
                items.Add(item);
            }

            OnFetchListItemsCompleted();
        }
    }
}